using System;
using System.Text;
using System.Reflection;
using System.Data.SqlClient;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

using Open.Data.Persistence;

namespace Open.Data.Persistence.Testing
{
    [TestClass]
    public class DeploymentTests
    {
        //Initialise test class
        [ClassInitialize()]
        public static void ClassInitialize(TestContext testContext)
        {

        }

        //Simulate multiple deployments of the same class with no data
        [TestMethod]
        public void DeploymentTest()
        {
            Context context = Singleton.Instance.GetContext();
            Deployment deployment = Singleton.Instance.CreateDeployment();
            deployment.Context = context;
            deployment.CheckNames = false; //We overwrite from different assemblies for testing purposes

            //Validate the assembly against the database
            deployment.DeploymentType = Open.Data.Persistence.DeploymentType.Deploy;
            deployment.DeploymentMode = Open.Data.Persistence.DeploymentMode.Update;
            deployment.PreDeployType += new Open.Data.Persistence.PreDeployTypeHandler(deployment_PreDeployType);

            for (int i = 1; i <= 6; i++)
            {
                context.Prefix = "Open.Data.Persistence.Testing.Step" + i;
                deployment.Deploy(System.Reflection.Assembly.GetExecutingAssembly());
            }
        }

        [TestMethod]
        public void DeploymentIndexTest()
        {
            CacheItem cacheitem = Provider.Instance.ReflectionCache.Lookup(typeof(Open.Data.Persistence.Testing.Person));
            Assert.IsTrue(cacheitem.Indexes.Count == 2, "Person definition does not contain 2 indexes.");
        }

        //Only deploy types that are authorised
        private void deployment_PreDeployType(object sender, Open.Data.Persistence.PreDeployTypeEventArgs e)
        {
            Deployment deployment = sender as Deployment;
            if (!e.Type.FullName.StartsWith(deployment.Context.Prefix)) e.Cancel = true;
        }
    }
}
